/*
 * Singularity Engine
 * Copyright (C) 2010 Vyacheslav Vorobyov, All rights reserved.
 * See LICENSE for full license information.
 */

package org.singularity.io;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;


/**
 * @author vjache
 *
 */
public class PrintOutput<VT> implements Output<VT> {

	private static final int BUFF_SIZE = 16*1024;
	private final PrintStream _ps;

	/**
	 * @throws UnsupportedEncodingException 
	 * 
	 */
	public PrintOutput(OutputStream aInputStream) throws UnsupportedEncodingException {
		this(aInputStream, false,"UTF8");
	}
	/**
	 * @throws UnsupportedEncodingException 
	 * 
	 */
	public PrintOutput(OutputStream aInputStream,boolean aAutoFlush, String aEncoding) throws UnsupportedEncodingException {
		_ps = new PrintStream(new BufferedOutputStream(aInputStream,BUFF_SIZE), aAutoFlush,aEncoding);
	}

	/* (non-Javadoc)
	 * @see org.singularity.io.Output#open()
	 */
	@Override
	public CloseablePipe<DME<VT>> open() {
		return new CloseablePipe<DME<VT>>() {

			@Override
			public void close() throws IOException {
				_ps.close();
			}

			@Override
			public void flush() throws IOException {
				_ps.flush();
			}

			@Override
			public void push(DME<VT> aItem) throws IOException {
				_ps.println(PrintOutput.this.dmeToString(aItem));
			}
		};
	}
	
	protected String dmeToString(DME<VT> aItem)
	{
		return aItem.toString();
	}

}
